package com.itheima.ydd.controller;

import com.itheima.ydd.common.FileInfo;
import com.itheima.ydd.common.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Optional;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Value("${youdianda.path}")
    private String basePath;

    @Value("${youdianda.path2}")
    private String frontPath;


    @PostMapping("/upload")
    public ResultData upload(MultipartFile file, HttpServletRequest request) {

        // 转存图片，截取文件的后缀名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 重新生产文件名
        String fileName = UUID.randomUUID() + suffix;

        // 转存
        try {
            File backendFile = new File(basePath + fileName);
            File frontFile = new File(frontPath + fileName);
            file.transferTo(backendFile);

            FileUtils.copyFile(backendFile, frontFile);

        } catch (IOException e) {
            e.printStackTrace();
        }

        //获取图片类型
        String mime = "";
        Optional<MediaType> mediaType = MediaTypeFactory.getMediaType(originalFilename);
        if (mediaType.isPresent()) {
            mime = mediaType.get().toString();
        }
        FileInfo fileInfo = new FileInfo();
        fileInfo.setSavePath("upload/images/" + fileName);
        fileInfo.setName(originalFilename);
        fileInfo.setMime(mime);
        fileInfo.setSize(file.getSize());

        return ResultData.ok("", fileInfo);
    }


}
